import { getFormatDate, getFormatHourMinute } from './datetime'
import { getUserInfobyId, getDeviceInfobyId, getGroupInfobyId } from '../api/userDeviceGroup'
import { request } from '../utils/request'
import { decryptAES } from '../utils/aes'

async function fillRoleData(members) {
  const res = []
  if (members) {
    for (let i = 0; i < members.length; i++) {
      if (members[i].type === 'user') {
        const userMsg = await getUserInfobyId(members[i].id)
        if (userMsg.code === 0) {
          res.push(convertUserInfoStruct(userMsg.data))
        }
      } else if (members[i].type === 'device') {
        const deviceMsg = await getDeviceInfobyId(members[i].id)
        if (deviceMsg.code === 0) {
          res.push(convertDeviceInfoStruct(deviceMsg.data))
        }
      } else if (members[i].type === 'userGroup') {
        const groupMsg = await getGroupInfobyId(members[i].id)
        if (groupMsg.code === 0) {
          res.push(convertGroupInfoStruct(groupMsg.data))
        }
      } else if (members[i].type === 'deviceGroup') {
        const groupMsg = await getGroupInfobyId(members[i].id)
        if (groupMsg.code === 0) {
          res.push(convertGroupInfoStruct(groupMsg.data))
        }
      } else {
      }
    }
  }
  return res
}

function convertUserInfoStruct(info) {
  return {
    type: 'user',
    id: parseInt(info.userId),
    userName: info.userName,
    name: info.personName ? info.personName : '',
    dept: '',
    deptCode: 0
  }
}

function convertDeviceInfoStruct(info) {
  return {
    type: 'device',
    id: parseInt(info.deviceId),
    deviceType: info.deviceType,
    name: info.deviceName ? info.deviceName : '',
    dept: '',
    deptCode: 0
  }
}

function convertGroupInfoStruct(info) {
  const obj = {
    id: parseInt(info.groupId),
    introduction: info.introduction,
    name: info.groupName ? info.groupName : '',
    dept: '',
    deptCode: 0
  }

  if (info.groupType === 1) {
    obj.type = 'userGroup'
  } else if (info.groupType === 2) {
    obj.type = 'deviceGroup'
  } else {
    obj.type = 'unknownGroup'
  }
  obj.member = convertGroupMemberStruct(obj.type, info.groupMember)

  return obj
}

function convertGroupMemberStruct(type, groupMember) {
  const member = []
  groupMember.forEach((memberItem) => {
    const item = {}
    item.id = memberItem.memberId
    item.name = memberItem.memberName
    if (type === 'userGroup') {
      item.type = 'user'
      item.userName = memberItem.memberAccount
    } else if (type === 'deviceGroup') {
      item.type = 'device'
    }
    member.push(item)
  })
  return member
}

async function requestMyTaskBriefList(deviceId, userId) {
  const { data } = await request.get('/task/myTaskBriefList', { params: { userId, deviceId } })
  return data
}

async function getMyPermission(userId, permType) {
  const { data } = await request.get('/permission/getInfo', { params: { userId, permType } })
  return data
}

async function getUserInfo(userId) {
  // const { data } = await request.get('/user/getInfo', { params: { userId } })  //不加密
  const { data } = await request.get('/user/getInfoEncrypt', { params: { userId } }) // 加密
  data.data = JSON.parse(decryptAES(data.data))
  return data
}

async function getTaskSetting() {
  const { data } = await request.get('/task/taskSettings')
  return data
}

function getPlanTimeStr(beginStamp, endStamp) {
  const beginDate = new Date(beginStamp)
  const endDate = new Date(endStamp)
  const beginDateStr = getFormatDate(beginDate)
  const endDateStr = getFormatDate(endDate)
  const diffDate = parseInt((new Date(endDateStr) - new Date(beginDateStr)) / 1000 / 60 / 60 / 24)

  const time = getFormatHourMinute(beginDate) + '~' + (diffDate ? `(+${diffDate}d)` : '') + getFormatHourMinute(endDate)
  return `${beginDateStr} ${time}`
}

function getBeginEndTimeStr(stamp) {
  const date = new Date(stamp)
  const ymd = getFormatDate(date)
  const time = getFormatHourMinute(date)
  return `${ymd} ${time}`
}

function getTaskTypeStr(type) {
  switch (type) {
    case 0:
      return '普通任务'
    case 1:
      return '工务作业'
    case 2:
      return '电务作业'
    case 3:
      return '巡道作业'
    case 4:
      return '列检作业'
    case 8:
      return '商检作业'
    case 7:
      return '调车作业'
    case 6:
      return '机务作业'
    case 5:
      return '其它作业'
    default:
      return '未知'
  }
}

function getTaskStateStr(state) {
  switch (state) {
    case 3:
      return '已批准'
    case 5:
      return '开始'
    case 6:
      return '结束'
    default:
      return '未知状态'
  }
}

function getRoleStr(role) {
  switch (role) {
    case 0:
      return '创建人'
    case 1:
      return '负责人'
    case 2:
      return '联络员'
    case 3:
      return '安全员'
    case 4:
      return '作业人员'
    case 5:
      return '巡道工'
    case 6:
      return '列检员'
    case 7:
      return '作业组长'
    default:
      return '未知'
  }
}

function getRoleDetailID(item) {
  if (item.type === 'user') {
    return `${item.userName}(${item.id})`
  } else if (item.type === 'device') {
    return `${item.id}`
  } else if (item.type === 'userGroup') {
    return `${item.id}`
  } else if (item.type === 'deviceGroup') {
    return `${item.id}`
  } else {
  }
}

function getRoleDetailType(item) {
  if (item.type === 'user') {
    return '人员'
  } else if (item.type === 'device') {
    if (item.deviceType === 2) {
      return '手持终端'
    } else if (item.deviceType === 3) {
      return '定位终端'
    }
  } else if (item.type === 'userGroup') {
    return '人员组'
  } else if (item.type === 'deviceGroup') {
    return '防护设备组'
  } else {
  }
}

function getTaskInfoRoleShow(showDataArray) {
  if (showDataArray) {
    return Array.from(showDataArray, (item) => getEntityShow(item)).toString()
  } else {
    return ''
  }
}

function getEntityShow(item) {
  let show = ''
  switch (item.type) {
    case 'user':
      if (item.name === '') show = item.userName
      else show = item.name
      break
    case 'device':
      if (item.deviceType === 2) {
        show = '手持-'
      } else if (item.deviceType === 3) {
        show = '定肩-'
      } else {
      }
      if (item.name === '') show += item.id
      else show += item.name
      break
    case 'userGroup':
      if (item.name === '') show = `人员组-${item.id}`
      else show = `人员组-${item.name}`
      break
    case 'deviceGroup':
      if (item.name === '') show = `设备组-${item.id}`
      else show = `设备组-${item.name}`
      break
    default:
      break
  }
  return show
}

function getWorkPlaceShow(workArea) {
  let show = ''
  if (workArea.places instanceof Array && workArea.places.length) {
    show = `站内：${workArea.places[0].name}`
  }
  return show
}

function getLJPlaceShow(workArea) {
  let show = ''
  if (workArea.places instanceof Array && workArea.places.length) {
    show = `站内：${workArea.places[0].name}`
  }
  return show
}

function getWorkRangeShow(areaKM) {
  const startKilo = areaKM.start.kilo ? areaKM.start.kilo : ''
  const startMeter = areaKM.start.meter ? areaKM.start.meter : ''
  const endKilo = areaKM.end.kilo ? areaKM.end.kilo : ''
  const endMeter = areaKM.end.meter ? areaKM.end.meter : ''
  return `K${startKilo}+${startMeter}m 至 K${endKilo}+${endMeter}m`
}

function getFenceIds(fences) {
  return Array.from(Object.keys(fences), (id) => parseInt(id))
}

async function requestMyWorkTypeTaskList(type, timeRange, timeType, station) {
  const { data } = await request.get('/task/taskBriefList', { params: { type, timeRange, timeType, station } })
  return data
}

export {
  requestMyWorkTypeTaskList,
  getMyPermission,
  getUserInfo,
  getTaskSetting,
  getPlanTimeStr,
  getRoleDetailID,
  getRoleDetailType,
  getBeginEndTimeStr,
  getTaskTypeStr,
  getTaskStateStr,
  getRoleStr,
  getTaskInfoRoleShow,
  getWorkPlaceShow,
  getLJPlaceShow,
  getWorkRangeShow,
  fillRoleData,
  getFenceIds,
  requestMyTaskBriefList,
  convertUserInfoStruct,
  convertDeviceInfoStruct,
  convertGroupInfoStruct,
  getEntityShow
}
